﻿
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.ComponentModel;
using System.Threading;

namespace System.Windows.Media.DirectShow.Filters
{
    public class DeviceCaptureSource : BaseFilter, ISourceFilter
    {

        private CaptureSource _captureSource;
        private AsyncOperation loadOperation;
        private DeviceCaptureSourceAudioPin audioPin;

        public DeviceCaptureSource()
        {
            this.loadOperation = AsyncOperationManager.CreateOperation(null);

            this.Pins.Add(audioPin = new DeviceCaptureSourceAudioPin(this));
        }

        public override string Name
        {
            get { return "Device Capture Source"; }
        }

        public CaptureSource CaptureSource
        {
            get
            {
                return _captureSource;
            }
            private set
            {
                if (this.State != FilterState.Stopped)
                    throw new InvalidOperationException("Cannot set source while filter is running or paused");

                _captureSource = value;
            }
        }

        public void LoadAsync(CaptureSource source)
        {
            this.CaptureSource = source;

            this.audioPin.PreparePin();
            source.Start();
        }

        protected override void RunInternal(TimeSpan start)
        {
            if (this.CaptureSource == null)
                throw new InvalidOperationException("No CaptureSource specified for this filter");

            base.RunInternal(start);

            this.loadOperation.Post(s => this.CaptureSource.Start(), null);
        }

        internal void PinReady(IPin pin)
        {
            this.loadOperation.Post(s =>
            {
                this.CaptureSource.Stop();
                OnLoadCompleted(new AsyncCompletedEventArgs(null, false, null));
            }, null);
        }

        #region ISourceFilter Members

        public event AsyncCompletedEventHandler LoadCompleted;

        protected virtual void OnLoadCompleted(AsyncCompletedEventArgs e)
        {
            if (LoadCompleted != null)
                LoadCompleted(this, e);
        }

        #endregion
    }
}
